<?php

namespace Admin\Frontend\Controllers;

use Admin\Models\school\XhschoolInfo;
use Admin\Models\server\XhserverBox;
use Exception;
use Helpers\HttpClient;
use Helpers\Tool;
use Helpers\Main;
use Helpers\Template;
use Helpers\Assets;
use Helpers\GmClient;
use Admin\Models\sys\XhsysConfig;
use Admin\Models\school\XhschoolBoxmark;
use Helpers\XhException;
use Modules\Power;
use Modules\School;
use Phalcon\Db\Column;
use function PHPSTORM_META\type;
use Services\MicroServer;

class ServerController extends ControllerBase
{

    private $boxEnum = [
        'status'    => [
            0 => '<i class="fa fa-circle fa-lg text-success"></i>',
            1 => '<i class="fa fa-circle fa-lg text-warning"></i>'
        ]
    ];

    /**
     * 微服务列表页面
     *
     * create by ck 20161028
     */
    public function microServerListAction()
    {
        $this->view->pick('server/microServerList');
        $this->assets->addJs('assets/jquery/jquery.form.js');
        Assets::easyUI('js/server/microServerList.js');
        Assets::select2();

        Main::showNavPosition();
        if (!Power::exist('Server_MicroServerList')) {
            return $this->sendViewError('无查看权限');
        }
        $listButtonArr = $listSearchArr = $formButtonArr = [];
        $listSearchArr[] = [
            'label' =>' 状态：',
            'type' => 'select',
            'id' => 'List_Search_status',
            'style' => 'width: 75px;',
            'data' => [0 => '--状态--',
                1 => '正常' ,
                2 => '下线'
            ]
        ];
        $listSearchArr[] = [
            'label' =>' 适用范围：',
            'type' => 'select',
            'id' => 'List_Search_scope',
            'style' => 'width: 75px;',
            'data' => [0 => '--状态--',
                'IDC' => 'IDC' ,
                'BOX' => 'BOX',
                'BASKET' => 'BASKET'
            ]
        ];
        $listSearchArr[] = ['type'=>'text', 'id'=>'List_Search_keyword', 'label'=>' 搜索：'];
        $listSearchArr[] = ['type'=>'text', 'id'=>'List_Search_schoolId', 'label'=>' 学校ID：', 'style'=>'width:60px;'];
        $listSearchArr[] = ['type'=>'text', 'id'=>'List_Search_serverId', 'label'=>' 服务器ID：', 'style'=>'width:60px;'];
        $listSearchArr[] = ['type'=>'text', 'id'=>'List_Search_classId', 'label'=>' 班级ID：', 'style'=>'width:60px;'];

        if (Power::exist('Server_MicroServerList_Add')) {
            $listButtonArr[] = ['plain' => 'true', 'id' => 'bt_list_add', 'text' => '新增', 'icon' => 'fa-plus'];
            $formButtonArr[] = ['id' => 'bt_form_add', 'text' => '保存', 'class' => 'disabled'];
        }
        if (Power::exist('Server_MicroServerList_Edit')) {
            $listButtonArr[] = ['plain' => 'true', 'id' => 'bt_list_start', 'text' => '启用', 'icon' => 'fa-play'];
            $listButtonArr[] = ['plain' => 'true', 'id' => 'bt_list_stop', 'text' => '停止', 'icon' => 'fa-pause'];
            $formButtonArr[] = ['id' => 'bt_form_edit', 'text' => '保存', 'class' => 'disabled'];
        }
        if (Power::exist('Server_MicroServerList_Del')) {
            $listButtonArr[] = ['plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash'];
        }
        $formButtonArr[] = ['id'=>'bt_form_back', 'text'=>'返回'];
        $formButtonArr[] = ['id'=>'bt_form_reset', 'text'=>'重置'];

        $schoolList['schList[]'] = School::getSchools();
        return $this->view->setVars([
            'List'          => Template::createList('List', 'XHServer_MicroServer', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, true),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
            'Form'          => Template::createForm('XHServer_MicroServer', $schoolList),
            'FormButton'    => Template::createButtonToolBar($formButtonArr),
        ]);
    }

    /**
     * 获取微服务列表数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by gby 20180830
     */
    public function getMicroServerDataAction()
    {
        try {
            $keyword = $this->request->getPost('keyword', 'string');
            $schoolId    = $this->request->getPost('schoolId', 'int');
            $serverId = $this->request->getPost('serverId');
            $classId = $this->request->getPost('classId');
            $scope = $this->request->getPost('scope');
            $status = $this->request->getPost('status', 'int');
            $page = $this->request->getPost('page', 'int');
            $size = $this->request->getPost('rows', 'int');
            $search = [];
            if ($keyword) {
                $search['keyword'] = $keyword;
            }
            if ($schoolId) {
                $search['schoolId'] = $schoolId;
            }
            if ($status == 1) {
                $search['status'] = true;
            } elseif ($status == 2) {
                $search['status'] = false;
            }
            if ($serverId) {
                $search['serverId'] = $serverId;
            }
            if ($classId) {
                $search['classId'] = $classId;
            }
            if ($scope && !empty($scope)) {
                $search['scope'] = $scope;
            }
            $result = MicroServer::getData($page, $size, $search);
            return $this->sendJsonResponse($result);
        } catch (XhException $e) {
            return $this->sendErrorResponse(400, $e->getMessage(), $e->getDescription());
        }
    }

//    /**
//     * 获取微服务列表数据
//     *
//     * create by ck 20161028
//     * modify by ck 20180629    重构
//     */
//    public function getMicroServerDataAction()
//    {
//        $serviceType = $this->request->getPost('serviceType', 'string');
//        $schoolId    = $this->request->getPost('schoolId', 'int');
//        $url         = Tool::getValue(Main::getConfigByName('microServer'), 'url');
//        if (!$url) {
//            return $this->sendErrorResponse(500, '缺少配置信息');
//        }
//        $params = [
//            'iPage'     => $this->request->getPost('page', 'int', 1),
//            'iPageSize' => $this->request->getPost('rows', 'int', 50)
//        ];
//        if ($serviceType) {
//            $params['sServiceType'] = $serviceType;
//        }
//        if ($schoolId) {
//            $params['iSchoolId'] = $schoolId;
//        }
//        $httpClient = new HttpClient($url);
//        $response   = $httpClient->get('gm_GetALLRegisitServer', $params);
//        $result     = $response->toArray();
//
//        if ($result['R'] != 200) {
//            return $this->sendErrorResponse(500, '获取失败', $response);
//        }
//        $data = $result['D'];
//        $data = json_decode($data, true);
//        Tool::runTimestamp($data['SrvList'], ['iUpdateTime']);
//        Tool::runEnum($data['SrvList'], $this->microEnum);
//        return $this->sendJsonResponse(['total' => $data['iTotalSize'], 'rows' => $data['SrvList'] ?: []]);

////        $searchArr = $this->request->getPost('search');
////        $K = [];
////        if(!empty($searchArr['sServiceType'])) $K['sServiceType'] = $searchArr['sServiceType'];
////        if(!empty($searchArr['iSchoolId'])) $K['iSchoolId'] = (int)$searchArr['iSchoolId'];
////        $microConfig = Main::getConfigByName('microServer');;
////        $microConfig or die('（109110002）无配置信息');
////        $K = $K ? base64_encode(json_encode($K)) : '';
////        $result = @file_get_contents($microConfig['url'] . 'gm_GetALLRegisitServer?K='.$K.'&Z=4');
////        json_decode($result) or die(json_encode(['error' => '返回结果非json！：' . $result, 'total' => 0, 'rows' => []]));
////        $result = json_decode($result, true);
////        if($result['R'] != 200) die(json_encode(['error' => $result['M'], 'total' => 0, 'rows' => []]));
////        $data = $result['D'];
////        $data = json_decode($data, true);
////        $data or $data = [];
////        foreach($data as $key => $server){
////            $data[$key]['iUpdateTime'] = date('Y-m-d H:i:s', $server['iUpdateTime']);
////            $data[$key]['iVaildRequest'] = $server['iVaildRequest'] ? '是' : '否';
////        }
////        echo json_encode(['total' => count($data), 'rows' => $data]);
//    }

//    /**
//     * 注册/更新服务状态
//     *
//     * create by ck 20161103
//     */
//    public function registerMicroServerAction()
//    {
//        $this->view->disable();
//        $this->request->isPost() or die;
//        Power::exist('Server_MicroServerList_Add') || Power::exist('Server_MicroServerList_Edit')
//            or die('（109110004）无操作权限');
//        $realData = Main::getRealData($this->request->getPost());
//        $realData = array_filter($realData);
////        $realData['ValidRequest'] = true;
//        $replaceArr = ['iServerId', 'iServerPort', 'iMPressPara', 'iCPressPara', 'iSchoolId'];
//        foreach ($realData as $key => $value) {
//            $realData[$key] = trim($value, '/');
//            if(in_array($key, $replaceArr)){
//                $realData[$key] = intval($realData[$key]);
//            }
//        }
//        $microConfig = Main::getConfigByName('microServer');
//        $microConfig or die('（109110003）无配置信息');
//        $K = base64_encode(json_encode($realData));
//        $result = @file_get_contents($microConfig['url'] . $microConfig['path'] . 'RegUpdateServer?K='.$K.'&Z=4');
//        $result = json_decode($result, true);
//        if($result['R'] != 200) die("（{$result['R']}）{$result['M']}");
//        echo 'success';
//    }

//    /**
//     * 停止服务
//     *
//     * create by ck 20161103
//     */
//    public function stopMicroServerAction()
//    {
//        $this->view->disable();
//        $this->request->isPost() or die;
//        Power::exist('Server_MicroServerList_Del') or die('（109110005）无操作权限！');
//        $ids = $this->request->getPost('ids');
//        $ids or die;
//        $ids = explode(',', $ids);
//        $microConfig = Main::getConfigByName('microServer');;
//        $microConfig or die('（109110006）无配置信息');
//        $idArr = [];
//        foreach($ids as $id){
//            $idArr[] = intval($id);
//        }
//        $K = [
//            'iVersion' => 1,
//            'Desc'     => '停止服务器',
//            'iServerId'=> $idArr
//        ];
//        $K = base64_encode(json_encode($K));
//        $result = @file_get_contents($microConfig['url'] . $microConfig['path'] . 'StopServer?K='.$K.'&Z=4');
//        $result = json_decode($result, true);
//        if($result['R'] != 200) die("（{$result['R']}）{$result['M']}");
//        echo '成功停止!';
//    }

    /**
     * 注册服务
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * @throws XhException
     *
     * create by gby 20180830
     * modify by fyh 20181109
     */
    public function registerMicroServerAction()
    {
        if (!Power::exist('Server_MicroServerList_Add')) {
            return $this->sendErrorResponse(400, '无权限操作');
        };
        $data = $this->request->getPost();
        $port = $this->request->getPost('port', 'int');

        if (!$data['serverType']) {
            return $this->sendErrorResponse(400, '应用编码不能为空');
        }
        if (!$port) {
            $data['port'] = 80;
        }
        if ($data['schList']) {
            $data['schoolIds'] = implode(',', $data['schList']);
        }
        $data['source'] = 0;
        unset($data['serverId'], $data['schList']);
        try {
            MicroServer::register($data);
            return $this->sendSuccessResponse('注册成功');
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        }
    }

    /**
     * 更新服务
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * @throws XhException
     *
     * create by gby 20180830
     * modify by fyh 20181112
     */
    public function updateMicroServerAction()
    {
        if (!Power::exist('Server_MicroServerList_Edit')) {
            return $this->sendErrorResponse(400, '无权限操作');
        };
        $data = $this->request->getPost();
        $port = $this->request->getPost('port', 'int');
        if ($data['schList']) {
            $data['schoolIds'] = implode(',', $data['schList']);
        }
        if (!$port) {
            $data['port'] = 80;
        }
        if (!$data['serverType']) {
            return $this->sendErrorResponse(400, '应用编码不能为空');
        }
        $data['source'] = 0;
        try {
            MicroServer::register($data);
            return $this->sendSuccessResponse('更新成功');
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        }
    }

    /**
     * 停用服务
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by gby 20180830
     */
    public function stopMicroServerAction()
    {
        if (!Power::exist('Server_MicroServerList_Edit')) {
            return $this->sendErrorResponse(400, '无权限操作');
        };
        $serverIds = $this->request->getPost('ids', 'int');
        $desc = $this->request->getPost('desc');
        if (!$serverIds) {
            return $this->sendErrorResponse(400, '缺少id');
        }
        $desc = isset($desc) ? $desc : '';
        try {
            MicroServer::stop($serverIds, $desc);
            return $this->sendSuccessResponse('成功停止');
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        }
    }

    /**
     * 启用服务
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by gby 20180830
     */
    public function startMicroServerAction()
    {
        if (!Power::exist('Server_MicroServerList_Edit')) {
            return $this->sendErrorResponse(400, '无权限操作');
        };
        $serverIds = $this->request->getPost('ids');
        $desc = $this->request->getPost('desc');
        if (!$serverIds) {
            return $this->sendErrorResponse(400, '缺少id');
        }
        $desc = isset($desc) ? $desc : '';
        try {
            MicroServer::start($serverIds, $desc);
            return $this->sendSuccessResponse('启用成功');
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        }
    }

    /**
     * 删除服务
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by gby 20180830
     */
    public function deleteMicroServerAction()
    {
        if (!Power::exist('Server_MicroServerList_Del')) {
            return $this->sendErrorResponse(400, '无权限操作');
        };
        $serverIds = $this->request->getPost('ids');
        $desc = $this->request->getPost('desc');
        if (!$serverIds) {
            return $this->sendErrorResponse(400, '缺少id');
        }
        $desc = isset($desc) ? $desc : '';
        try {
            MicroServer::delete($serverIds, $desc);
            return $this->sendSuccessResponse('删除成功');
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        }
    }
//    /**
//     * 删除服务
//     *
//     * create by ck 20161125
//     */
//    public function deleteMicroServerAction()
//    {
//        $this->view->disable();
//        $this->request->isPost() or die;
//        Power::exist('Server_MicroServerList_Del') or die('（109110007）无操作权限！');
//        $ids = $this->request->getPost('ids');
//        $ids or die;
//        $ids = explode(',', $ids);
//        $microConfig = Main::getConfigByName('microServer');;
//        $microConfig or die('（109110008）无配置信息');
//        $idArr = [];
//        foreach($ids as $id){
//            $idArr[] = intval($id);
//        }
//        $K = ['iServerId'=> $idArr];
//        $K = base64_encode(json_encode($K));
//        $result = @file_get_contents($microConfig['url'] . 'gm_deleteserver?K='.$K.'&Z=4');
//        $result = json_decode($result, true);
//        if($result['R'] != 200) die("（{$result['R']}）{$result['M']}");
//        echo '成功删除!';
//    }

    /**
     * 更改盒子学校ID主页
     *
     * create by ck 20161116
     * modify by ck 20170524    更改权限
     */
    public function boxServerListAction()
    {
        $this->view->pick('server/boxServerList');
        Assets::easyUI('js/server/boxServerList.js');
        Main::showNavPosition();
        Power::exist('Server_BoxList') or die(Main::showMessageModal('对不起，您没有查看此页面的权限！', 109110009));
        $changeArr = Main::getConfigByName('cBoxInfo', true);
        $changeArr = $changeArr['changeRecord'];
        $changeArr = json_decode($changeArr, true);
        $boxButtonArr = $markButtonArr = [];
        if (Power::exist('Server_BoxList_Change')) {
            if (!empty($changeArr['change'])) {
                $boxButtonArr[] = [
                    'id'=>'bt_list_Rollback','text'=>'还原','icon'=>'fa-backward','style'=>'margin-left:10px;'
                ];
            } else {
                $boxButtonArr[] = [
                    'id'=>'bt_list_Change','text'=>'切换','icon'=>'fa-exchange','style'=>'margin-left:10px;'
                ];
            }
        }
        $boxButtonArr[]  = ['id'=>'bt_list_State','text'=>'查看状态','icon'=>'fa-eye'];
        if (Power::exist('Server_BoxList_Edit')) {
            $boxButtonArr[] = ['id' => 'bt_list_Refresh', 'text' => '刷新', 'icon' => 'fa-refresh'];
//            $boxButtonArr[]  = ['plain'=>'true' ,'id'=>'bt_list_Port', 'text'=>'修改端口', 'icon'=>'fa-pencil'];
            $boxButtonArr[] = [
                'plain' => 'true', 'id' => 'bt_list_enableNotice', 'text' => '开启通知', 'icon' => 'fa-chain'
            ];
            $boxButtonArr[] = [
                'plain' => 'true', 'id' => 'bt_list_disableNotice', 'text' => '关闭通知', 'icon' => 'fa-chain-broken'
            ];
            $markButtonArr[] = ['id'=>'bt_MarkList_Add','text'=>'新增','icon'=>'fa-plus'];
            $markButtonArr[] = ['id'=>'bt_MarkList_Del','text'=>'删除','icon'=>'fa-trash'];
        }
        $this->view->setVars([
            'List'      => Template::createList('List', 'XHServer_Box', [
                'buttonToolbar' => Template::createButtonToolBar($boxButtonArr),
                'tableAttr'
            ]),
            'MarkList'  => Template::createList('MarkList', 'XHServer_BoxMark', [
                'buttonToolbar' => Template::createButtonToolBar($markButtonArr)
            ])
        ]);
    }

    /**
     * 获取盒子列表
     *
     * @param bool $flush       --更改后刷新
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20161125
     * modify by ck 20161126
     * modify by ck 20161207    ping返回格式变化
     * modify by ck 20161208    修复历史学校记录BUG
     * modify by ck 20161228    修复历史记录BUG
     * modify by ck 20161229    更改显示逻辑
     * modify by ck 20170121    学校历史信息以json储存，防止配置管理更改
     */
    public function getBoxListAction($flush = false)
    {
        $this->view->disable();
        if ($flush) {
            error_reporting(E_ERROR);
        }
        $refresh = $this->request->getPost('refresh', 'string');
        $notice  = $this->request->getPost('notice', 'string');
        $boxInfo = XhserverBox::find()->toArray();
        $boxInfo = array_column($boxInfo, null, 'iSchoolId');
        $schoolNameArr = XhschoolInfo::getSchoolSupportArray();
        foreach ($schoolNameArr as $schId => $schName) {
            $boxInfo[$schId]['iSchoolId'] = $schId;
            $boxInfo[$schId]['sSchoolName'] = $schName;
        }

        //获取配置信息
        $changeArr = Main::getConfigByName('cBoxInfo', true);
        $changeArr = $changeArr['changeRecord'];
        $changeArr = json_decode($changeArr, true);

        //刷新则重新获取信息
        if ($refresh || $flush) {
            $config = Main::getConfigByName('cBoxUrl');

            //重置服务及网络状态
            foreach ($boxInfo as $index => $info) {
                $boxInfo[$index]['bServerStatus'] = 0;
                $boxInfo[$index]['bNetStatus'] = 0;
            }

            //获取盒子学校ID
            $gmClient = new GmClient();
            $gmClient->connect($config['ip'], $config['port']) or die(Main::showMessageModal('盒子连接失败！'));
            $gmStr = '//gm ping box';
            $gmClient->writeAndReadChatMsg($gmStr, $result);

            //过滤结果并提取学校ID及IP
            foreach ($result as $key => $value) {
                $result[$key] = iconv('gb2312', 'utf-8', $value);
                if (strpos($result[$key], '中心服务器')) {
                    unset($result[$key]);
                    continue;
                }
                $value = explode(',', $value);
                $infoArr = [];
                foreach ($value as $field) {
                    $temp = explode(':', $field);
                    $infoArr[$temp[0]] = $temp[1];
                }
                if (!isset($infoArr['schlId']) || !$infoArr['schlId']) {
                    continue;
                }
                $boxInfo[$infoArr['schlId']]['iSchoolId'] = $infoArr['schlId'];
                $boxInfo[$infoArr['schlId']]['bServerStatus'] = 1;
                $boxInfo[$infoArr['schlId']]['sBoxIp'] = $infoArr['ip'];
                $boxInfo[$infoArr['schlId']]['sBoxWIp'] = $infoArr['wIp'];
                $boxInfo[$infoArr['schlId']]['sBoxVersion'] = $infoArr['ver'];
                $boxInfo[$infoArr['schlId']]['tStartTime'] = date('Y-m-d H:i:s', $infoArr['startT']);
            }

            //获取网络状态
            $netInfo = file($config['netUrl']);
            $successPort = $failurePort = [];
            foreach ($netInfo as $info) {
                $info = explode(' ', $info);
                if (!isset($info[2])) {
                    continue;
                }
                $port = explode(':', $info[3]);
                $port = trim(end($port));
                if (!is_numeric($port)) {
                    continue;
                }
                if ($info[2] == '[SUCCESS]') {
                    $successPort[] = $port;
                } else {
                    $failurePort[] = $port;
                }
            }
            foreach ($boxInfo as $index => $info) {
                if (in_array($info['iPortNum'], $successPort)) {
                    $boxInfo[$index]['bNetStatus'] = 1;
                }
            }

            $changeStatusRecord = [];
            //更新数据库记录
            $time = date('Y-m-d H:i:s');
            foreach ($boxInfo as $info) {
                if ($info['iSchoolId'] == 900090009) {
                    continue;
                }
                //过滤切换学校
                if (isset($changeArr['change'])) {
                    if ($info['iSchoolId'] == $changeArr['change']['new']) {
                        continue;
                    }
                }
                if (isset($changeArr['before'])) {
                    if ($info['iSchoolId'] == $changeArr['before']['new']) {
                        continue;
                    }
                }
                $obj = XhserverBox::findFirst([
                    'conditions' => 'iSchoolId = ?0',
                    'bind'       => [$info['iSchoolId']],
                    'bindType'   => [Column::BIND_PARAM_INT]
                ]);
                if (!$obj) {
                    $obj = new XhserverBox();
                    $obj->tCreateTime = $time;
                }
                $info['tUpdateTime'] = $time;
                $obj->assign($info);
                if ($obj->bNotice) {
                    //判断是否变更状态
                    if ($obj->hasSnapshotData()) {
                        if ($obj->hasChanged('bServerStatus')) {
                            $changeStatusRecord[$obj->iSchoolId]['bServerStatus'] = boolval($obj->bServerStatus);
                        }
                        if ($obj->hasChanged('bNetStatus')) {
                            $changeStatusRecord[$obj->iSchoolId]['bNetStatus'] = boolval($obj->bNetStatus);
                        }
                    } else {
                        if ($obj->bServerStatus) {
                            $changeStatusRecord[$obj->iSchoolId]['bServerStatus'] = true;
                        }
                        if ($obj->bNetStatus) {
                            $changeStatusRecord[$obj->iSchoolId]['bNetStatus'] = true;
                        }
                    }
                }
                $obj->save();
            }

            //需通知变更状态信息
            if ($changeStatusRecord && $notice && $config['noticePhone']) {
                $msg = ['盒子状态变更通知：'];
                foreach ($changeStatusRecord as $schId => $record) {
                    $tempMsg = "学校{$schId}({$schoolNameArr[$schId]})：";
                    if (isset($record['bServerStatus'])) {
                        $tempMsg .= '服务' . ($record['bServerStatus'] ? '上线' : '下线');
                    }
                    if (isset($record['bNetStatus'])) {
                        isset($record['bServerStatus']) and $tempMsg .= '，';
                        $tempMsg .= '网络' . ($record['bServerStatus'] ? '上线' : '下线');
                    }
                    $msg[] = $tempMsg;
                }
                $msg = implode('；', $msg);
                $result = Tool::sendMsgToPhone($config['noticePhone'], $msg);
                Main::createCommitLog(
                    'server',
                    'box',
                    'notice',
                    ['phone' => $config['noticePhone'], 'msg' => $msg],
                    null,
                    '短信发送' . ($result ? '成功' : '失败')
                );
            }

            //如果为后台刷新，则终止程序
            if ($flush) {
                die('刷新数据库成功！');
            }
        }

        //获取更改记录，信息填充到原记录
//        $transField = ['sBoxIp', 'sBoxWIp', 'sBoxVersion', 'bServerStatus', 'tStartTime'];
        $transField = ['bServerStatus'];
        if (isset($changeArr['change'])) {
            $oldSchId = $changeArr['change']['old'];
            $newSchId = $changeArr['change']['new'];
            $tempBoxInfo = $boxInfo[$newSchId];
            foreach ($tempBoxInfo as $field => $value) {
                if (in_array($field, $transField)) {
                    $boxInfo[$oldSchId][$field] = $value;
                }
            }
            $boxInfo[$oldSchId]['sSchoolName'] .= '(<font color="#FF0033">' .
                $boxInfo[$newSchId]['sSchoolName'] . '</font>)';
            $boxInfo[$oldSchId]['bServerStatus'] = 1;
            $boxInfo[$newSchId]['bServerStatus'] = 0;
            if (isset($changeArr['before']) && $changeArr['before']['new'] != 900090009) {
                $oldSchId = $changeArr['before']['old'];
                $newSchId = $changeArr['before']['new'];
                $tempBoxInfo = $boxInfo[$newSchId];
                foreach ($tempBoxInfo as $field => $value) {
                    if (in_array($field, $transField)) {
                        $boxInfo[$oldSchId][$field] = $value;
                    }
                }
                $boxInfo[$oldSchId]['sSchoolName'] .= '(<font color="#FF0033">' .
                    $boxInfo[$newSchId]['sSchoolName'] . '</font>)';
                $boxInfo[$oldSchId]['bServerStatus'] = 1;
                $boxInfo[$newSchId]['bServerStatus'] = 0;
            }
        }
        unset($boxInfo[900090009]);

        //根据服务/网络/版本状态排序
        $serStatus = $netStatus = $verStatus = [];
        foreach ($boxInfo as $key => $row) {
            $serStatus[$key] = $row['bServerStatus'];
            $netStatus[$key] = $row['bNetStatus'];
            $verStatus[$key] = $row['sBoxVersion'];
        }
        array_multisort($serStatus, SORT_DESC, $netStatus, SORT_DESC, $verStatus, SORT_DESC, $boxInfo);

        //处理状态图标
        foreach ($boxInfo as $index => $rowData) {
            //删除无状态且无名称（未上线）学校记录
            if (!$rowData['sSchoolName'] && !$rowData['bServerStatus'] && !$rowData['bNetStatus']) {
                unset($boxInfo[$index]);
                continue;
            }
            $boxInfo[$index]['bServerStatus'] = '<i class="fa fa-circle fa-lg text-' .
                ($rowData['bServerStatus'] ? 'success' : ($rowData['sBoxVersion'] ? 'warning' : 'muted')). '"></i>';
            $boxInfo[$index]['bNetStatus'] = '<i class="fa fa-circle fa-lg text-' .
                ($rowData['bNetStatus'] ? 'success' : ($rowData['iPortNum'] || $rowData['sBoxVersion'] ?
                    'warning' : 'muted')). '"></i>';
            $boxInfo[$index]['bNotice'] = $rowData['bNotice'] ? '是' : '否';
        }

        return $this->response->setJsonContent(['total' => count($boxInfo), 'rows' => array_values($boxInfo)]);

//        $this->view->disable();
//
//        //读取学校列表
//        $config = Main::getConfigByName('cBoxUrl');
//        $xml = file_get_contents($config['schoolXmlUrl']);
//        $xml = simplexml_load_string($xml);
//        $schoolArr = [];    //学校ID-名称数组
//
//        //处理xml获取学校
//        foreach($xml->children() as $school){
//            $schoolInfo = get_object_vars($school);
//            $schoolArr[$schoolInfo['id']] = ['iSchoolId' => $schoolInfo['id'], 'sSchoolName' => $schoolInfo['name']];
//        }
//
//        //获取盒子学校ID
//        $gmClient = new GmClient();
//        $gmClient->connect($config['ip'], $config['port']) or die(Main::showMessageModal('盒子连接失败！', 109110010));
//        $gmStr = '//gm ping box';           //ping盒子命令
//        $gmClient->writeAndReadChatMsg($gmStr, $result);
//
//        //过滤结果并提取学校ID及IP
//        $boxIdArr = [];
//        foreach($result as $key => $value){
//            $result[$key] = iconv('gb2312', 'utf-8', $value);
//            if(strpos($result[$key], '中心服务器')){
//                unset($result[$key]);
//                continue;
//            }
//            $value = explode(',', $value);
//            $infoArr = [];
//            foreach($value as $field){
//                $temp = explode(':', $field);
//                $infoArr[$temp[0]] = $temp[1];
//            }
//            if(!isset($infoArr['schlId']) || !$infoArr['schlId']) continue;
//            $boxIdArr[] = $infoArr['schlId'];
//            $schoolArr[$infoArr['schlId']]['bExistBox'] = '<i class="fa fa-circle fa-lg text-success"></i>';
//            $schoolArr[$infoArr['schlId']]['sBoxIp'] = $infoArr['ip'];
//            $schoolArr[$infoArr['schlId']]['sBoxWIp'] = $infoArr['wIp'];
//            $schoolArr[$infoArr['schlId']]['sBoxVersion'] = $infoArr['ver'];
//            $schoolArr[$infoArr['schlId']]['sStartTime'] = date('Y-m-d H:i:s', $infoArr['startT']);
//        }
//
//        //记录盒子学校ID
//        XhsysConfig::createArrRecord('cBoxInfo', 'boxId', $boxIdArr);
//
//        //获取历史盒子信息，合并新信息存入数据库
//        $boxInfo = Main::getConfigByName('cBoxInfo', true);
//        $boxHisInfo = isset($boxInfo['boxHisInfo']) ? array_column(json_decode($boxInfo['boxHisInfo'], true), null, 'iSchoolId') : [];
//        $boxTempInfo = $schoolArr;
//        foreach($boxTempInfo as $key => $value){
//            if(!isset($value['bExistBox'])) unset($boxTempInfo[$key]);
////            unset($boxTempInfo[$key]['iSchoolId']);
//            unset($boxTempInfo[$key]['sSchoolName']);
//            unset($boxTempInfo[$key]['bExistBox']);
//        }
//        $boxNewInfo = $boxHisInfo;
//        foreach($boxTempInfo as $key => $value){
//            $boxNewInfo[$key] = $value;
//        }
//
//        $historySchoolIdArr = array_column($boxHisInfo, 'iSchoolId');
//
//        //去除被修改ID（盒子修改到目标学校）
//        $changeRecord = isset($boxInfo['changeRecord']) ? $boxInfo['changeRecord'] : [];
//        $historySchoolIdArr = array_merge($historySchoolIdArr, $boxIdArr);
//        $historySchoolIdArr = array_unique($historySchoolIdArr);
//        if(isset($changeRecord['before']['new'])){
//            $schoolArr[$changeRecord['before']['new']]['sSchoolName'] = "<font style='color: #FF0033'>{$schoolArr[$changeRecord['before']['new']]['sSchoolName']}</font>";
//            $index = array_search($changeRecord['before']['new'], $historySchoolIdArr);
//            if($index !== false){
//                unset($historySchoolIdArr[$index]);
//                foreach($boxNewInfo as $key => $value){
//                    if($changeRecord['before']['new'] == $value['iSchoolId']){
//                        unset($boxNewInfo[$key]);
//                    }
//                }
////                unset($boxNewInfo[$index]);
//            }
//        }
//        if(isset($changeRecord['change']['new'])){
//            $schoolArr[$changeRecord['change']['new']]['sSchoolName'] = "<font style='color: #FF0033'>{$schoolArr[$changeRecord['change']['new']]['sSchoolName']}</font>";
//            $index = array_search($changeRecord['change']['new'], $historySchoolIdArr);
//            if($index !== false){
//                unset($historySchoolIdArr[$index]);
//                foreach($boxNewInfo as $key => $value){
//                    if($changeRecord['change']['new'] == $value['iSchoolId']){
//                        unset($boxNewInfo[$key]);
//                    }
//                }
////                unset($boxNewInfo[$index]);
//            }
//        }
//        XhsysConfig::createArrRecord('cBoxInfo', 'boxHisInfo', json_encode(array_values($boxNewInfo)));
//
//        //历史中存在，ping不通标记
//        $missSchoolIdArr = array_diff($historySchoolIdArr, $boxIdArr);
//        foreach($missSchoolIdArr as $missId){
//            $schoolArr[$missId]['bExistBox'] = '<i class="fa fa-circle fa-lg text-warning"></i>';
//            isset($boxHisInfo[$missId]['sBoxIp']) and $schoolArr[$missId]['sBoxIp'] = "<font style='color: #edbc6c'>{$boxHisInfo[$missId]['sBoxIp']}</font>";
//            isset($boxHisInfo[$missId]['sBoxWIp']) and $schoolArr[$missId]['sBoxWIp'] = "<font style='color: #edbc6c'>{$boxHisInfo[$missId]['sBoxWIp']}</font>";
//            isset($boxHisInfo[$missId]['sBoxVersion']) and $schoolArr[$missId]['sBoxVersion'] = "<font style='color: #edbc6c'>{$boxHisInfo[$missId]['sBoxVersion']}</font>";
//            isset($boxHisInfo[$missId]['sStartTime']) and $schoolArr[$missId]['sStartTime'] = "<font style='color: #edbc6c'>{$boxHisInfo[$missId]['sStartTime']}</font>";
//        }
//
//        if(isset($changeRecord['change'])){
//            $schoolArr[$changeRecord['change']['old']]['sSchoolName'] .= ('(' . $schoolArr[$changeRecord['change']['new']]['sSchoolName'] . ')');
//            $schoolArr[$changeRecord['change']['old']]['bExistBox'] = $schoolArr[$changeRecord['change']['new']]['bExistBox'];
//            $schoolArr[$changeRecord['change']['old']]['sBoxIp'] = $schoolArr[$changeRecord['change']['new']]['sBoxIp'];
//            $schoolArr[$changeRecord['change']['old']]['sBoxWIp'] = $schoolArr[$changeRecord['change']['new']]['sBoxWIp'];
//            $schoolArr[$changeRecord['change']['old']]['sBoxVersion'] = $schoolArr[$changeRecord['change']['new']]['sBoxVersion'];
//            $schoolArr[$changeRecord['change']['old']]['sStartTime'] = $schoolArr[$changeRecord['change']['new']]['sStartTime'];
//            unset($schoolArr[$changeRecord['change']['new']]['bExistBox']);
//            unset($schoolArr[$changeRecord['change']['new']]['sBoxIp']);
//            unset($schoolArr[$changeRecord['change']['new']]['sBoxWIp']);
//            unset($schoolArr[$changeRecord['change']['new']]['sBoxVersion']);
//            unset($schoolArr[$changeRecord['change']['new']]['sStartTime']);
//        }
//        if(isset($changeRecord['before'])){
//            $schoolArr[$changeRecord['before']['old']]['bExistBox'] = $schoolArr[$changeRecord['before']['new']]['bExistBox'];
//            $schoolArr[$changeRecord['before']['old']]['sBoxIp'] = $schoolArr[$changeRecord['before']['new']]['sBoxIp'];
//            $schoolArr[$changeRecord['before']['old']]['sBoxWIp'] = $schoolArr[$changeRecord['before']['new']]['sBoxWIp'];
//            $schoolArr[$changeRecord['before']['old']]['sBoxVersion'] = $schoolArr[$changeRecord['before']['new']]['sBoxVersion'];
//            $schoolArr[$changeRecord['before']['old']]['sStartTime'] = $schoolArr[$changeRecord['before']['new']]['sStartTime'];
//            unset($schoolArr[$changeRecord['before']['new']]['bExistBox']);
//            unset($schoolArr[$changeRecord['before']['new']]['sBoxIp']);
//            unset($schoolArr[$changeRecord['before']['new']]['sBoxWIp']);
//            unset($schoolArr[$changeRecord['before']['new']]['sBoxVersion']);
//            unset($schoolArr[$changeRecord['before']['new']]['sStartTime']);
//        }
//        foreach($schoolArr as $key => $value){
//            if(!empty($value['bExistBox'])) continue;
//            $schoolArr[$key]['bExistBox'] = '<i class="fa fa-circle-o fa-lg text-muted"></i>';
//        }
//        unset($schoolArr['900090009']);
//        echo json_encode(['total' => count($schoolArr), 'rows' => array_values($schoolArr)]);
    }

    /**
     * 更改学校端口
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170427
     */
    public function changeBoxPortAction()
    {
        $this->view->disable();
        $schoolId = $this->request->getPost('schoolId', 'int');
        $port = $this->request->getPost('port', 'int');
        $port or $port = 0;
        $schoolId or die(json_encode(['error' => '缺少学校ID！']));
        $obj = XhserverBox::findFirst([
            'conditions' => 'iSchoolId = ?1',
            'bind'       => [1 => $schoolId],
            'bindType'   => [1 => Column::BIND_PARAM_INT]
        ]);
        $obj or die(json_encode(['error' => '无对应学校记录！']));
        $obj->iPortNum = $port;
        $obj->save() or die(json_encode(['error' => '保存失败！']));
        Main::createCommitLog('server', 'box', 'edit', $obj, $obj->iSBId, '更改端口');
        return $this->response->setJsonContent($obj);
    }

    /**
     * 启用/关闭通知
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170427
     */
    public function changeBoxNoticeAction()
    {
        $this->view->disable();
        $schoolId = $this->request->getPost('schoolId', 'int');
        $notice = $this->request->getPost('notice', 'int', 0);
        $schoolId or die(json_encode(['error' => '缺少学校ID！']));
        $obj = XhserverBox::findFirst([
            'conditions' => 'iSchoolId = ?1',
            'bind'       => [1 => $schoolId],
            'bindType'   => [1 => Column::BIND_PARAM_INT]
        ]);
        $obj or die(json_encode(['error' => '无对应学校记录！']));
        $obj->bNotice = $notice;
        $obj->save() or die(json_encode(['error' => '保存失败！']));
        Main::createCommitLog('server', 'box', 'edit', $obj, $obj->iSBId, $notice ? '开启通知' : '关闭通知');
        return $this->response->setJsonContent($obj);
    }

    /**
     * 更改盒子学校ID
     *
     * create by ck 20161117
     */
    public function changeBoxIdAction()
    {
        $this->view->disable();
        Power::exist('Server_BoxList_Change') or die('（109110011）无操作权限！');
        $this->request->isPost() or die;

        //检查是否新老学校ID齐全
        $oldSchoolId = 3563;//$this->request->getPost('oldSchoolId', 'int');
        $newSchoolId = $this->request->getPost('newSchoolId', 'int');
        $oldSchoolId && $newSchoolId or die('（109110012）缺少学校ID！');

        //有操作记录则报错，需还原后才可继续操作
        $changeArr = Main::getConfigByName('cBoxInfo', true);
        $changeArr = $changeArr['changeRecord'];
        $changeArr = json_decode($changeArr, true);
        if ($changeArr) {
            die('（109110013）请先还原上次更改后操作！');
        }

        //获取盒子学校ID
        $config = Main::getConfigByName('cBoxUrl');
        $gmClient = new GmClient();
        $gmClient->connect($config['ip'], $config['port']) or die(Main::showMessageModal('盒子连接失败！', 109110010));
        $gmStr = '//gm ping box';
        $gmClient->writeAndReadChatMsg($gmStr, $result);

        //过滤结果并提取学校ID及IP
        $existSchId = [];
        foreach ($result as $key => $value) {
            $result[$key] = iconv('gb2312', 'utf-8', $value);
            if (strpos($result[$key], '中心服务器')) {
                unset($result[$key]);
                continue;
            }
            $value = explode(',', $value);
            $infoArr = [];
            foreach ($value as $field) {
                $temp = explode(':', $field);
                $infoArr[$temp[0]] = $temp[1];
            }
            if (!isset($infoArr['schlId']) || !$infoArr['schlId']) {
                continue;
            }
            $existSchId[] = $infoArr['schlId'];
        }

        $msg = '';                      //操作消息
        $changeArr = [];                //转换记录
        $flag = false;                  //切换到学海教育平台标记

        //如果新学校ID已存在则先将新学校切换到学海教育平台
        if (in_array($newSchoolId, $existSchId)) {
            $result = $this->changeBoxSchoolId($gmClient, $newSchoolId, 900090009);
            $result or die('（109110015）执行失败！');
            $msg .= $result;
            $flag = true;
            $changeArr['before'] = ['old' => $newSchoolId, 'new' => 900090009];
            sleep(2);       //间隔两秒防止切换延时问题
        }
        //切换学校ID
        $result = $this->changeBoxSchoolId($gmClient, $oldSchoolId, $newSchoolId);
        if ($result) {
            $msg .= $result;
            $changeArr['change'] = ['old' => $oldSchoolId, 'new' => $newSchoolId];
        } else {
            //还原新学校所做操作
            if ($flag) {
                $result = $this->changeBoxSchoolId($gmClient, 900090009, $newSchoolId);
                if (!$result) {
                    $changeArr['change'] = $changeArr['before'];
                    unset($changeArr['before']);
                    XhsysConfig::createArrRecord('cBoxInfo', 'changeRecord', json_encode($changeArr));
                    die("（109110016）执行失败！学校{$newSchoolId}已被改为900090009，请手动重置！");
                }
            }
            die('（109110017）执行失败！');
        }
        //成功后写入信息并提示消息
        XhsysConfig::createArrRecord('cBoxInfo', 'changeRecord', json_encode($changeArr));
        Main::createCommitLog('server', 'boxChange', 'change', ['change'=>$changeArr,'msg'=>$msg], null, '更改盒子ID');
        echo $msg;
        $this->getBoxListAction(true);
    }

    /**
     * 还原盒子更改清空
     *
     * create by ck 20161117
     */
    public function rollbackBoxIdAction()
    {
        $this->view->disable();
        Power::exist('Server_BoxList_Change') or die('（109110018）无操作权限！');
        $boxInfo = Main::getConfigByName('cBoxInfo', true);
        $changeArr = $boxInfo['changeRecord'];
        $changeArr = json_decode($changeArr, true);
        if (!$changeArr) {
            die('（109110019）无操作记录，无法还原！');
        }
        $config = Main::getConfigByName('cBoxUrl');
        $gmClient = new GmClient();
        $gmClient->connect($config['ip'], $config['port']) or die(Main::showMessageModal('盒子连接失败！', 109110020));
        $msg = '';
        $result = $this->changeBoxSchoolId($gmClient, $changeArr['change']['new'], $changeArr['change']['old']);
        $result or die('（109110021）执行失败！');
        $msg .= $result;
        if (isset($changeArr['before'])) {
            sleep(2);
            $result = $this->changeBoxSchoolId($gmClient, $changeArr['before']['new'], $changeArr['before']['old']);
            if (!$result) {
                $changeArr['change'] = $changeArr['before'];
                unset($changeArr['before']);
                XhsysConfig::createArrRecord('cBoxInfo', 'changeRecord', json_encode($changeArr));
                die("（109110022）执行失败！学校{$changeArr['change']['new']}到{$changeArr['change']['old']}未还原成功！");
            }
            $msg .= ', ' . $result;
        }

        //成功后清空修改记录并提示消息
        XhsysConfig::createArrRecord('cBoxInfo', 'changeRecord', json_encode([]));
        Main::createCommitLog('server', 'boxChange', 'rollback', $changeArr, null, '更改盒子ID');
        echo $msg;
        $this->getBoxListAction(true);
    }

    /**
     * 更改盒子的学校ID
     *
     * @param $gmClient         --GM消息类
     * @param $oldSchoolId      --老学校ID
     * @param $newSchoolId      --新学校ID
     * @return bool|string
     *
     * create by ck 20161117
     */
    private function changeBoxSchoolId(GmClient $gmClient, $oldSchoolId, $newSchoolId)
    {
        if (APP_DEV) {
            return 'success';
        }
        $result = null;
        $gmStr = '//gm switchBoxSchl ' . $oldSchoolId . ' ' . $newSchoolId;
        $gmClient->writeAndReadChatMsg($gmStr, $result);
        foreach ($result as $key => $value) {
            $result[$key] = iconv('gb2312', 'utf-8', $value);
        }
        $result = array_values(array_filter($result));
        if (!$result) {
            return false;
        }
        return implode(', ', $result);
    }

    /**
     * 获取学校盒子备注
     *
     * create by ck 20161213
     */
    public function getBoxMarkListAction()
    {
        $this->view->disable();
        $schoolId = $this->request->getPost('iSchoolId', 'int');
        $parameters = [
            'colmuns'    => 'iBMId,sContent,tCreateDate',
            'conditions' => "bDelete = 0 and iSchoolId = {$schoolId}"
        ];
        $total = XhschoolBoxmark::count($parameters);
        $rows = XhschoolBoxmark::find($parameters)->toArray();
        echo json_encode(['total' => $total, 'rows' => $rows]);
    }

    /**
     * 根据传入学校ID及备注内容为盒子增加备注
     *
     * create by ck 20161213
     */
    public function addBoxMarkAction()
    {
        $this->view->disable();
        Power::exist('Server_BoxList_Edit') or die;
        $schoolId = $this->request->getPost('iSchoolId', 'int');
        $content = $this->request->getPost('sContent', 'string');
        $schoolId && $content or die;
        $mark = XhschoolBoxmark::createRecord($schoolId, $content);
        $mark->insertData() or die;
        Main::createCommitLog('server', 'boxMark', 'add', $mark, $mark->iBMId);
    }

    /**
     * 根据备忘ID删除记录
     *
     * create by ck 20161213
     */
    public function delBoxMarkAction()
    {
        $this->view->disable();
        $ids = $this->request->getPost('ids', 'string');
        $ids or die;
        XhschoolBoxmark::deleteRecordById(explode(',', $ids)) or die('删除失败！');
        Main::createCommitLog('server', 'boxMark', 'del', $ids, null, '批量删除');
        echo '删除成功！';
    }

    /**
     * 显示盒子状态页面
     *
     * create by ck 20170118
     */
    public function showBoxStateAction()
    {
        $this->view->pick('server/showBoxState');
        Assets::importJs('js/server/showBoxState.js');
        Power::exist('Server_BoxList') or die(Main::showMessageModal('对不起，您没有查看此页面的权限！', 109110023));
    }

    /**
     * 根据学校ID获取盒子状态
     *
     * create by ck 20170119
     * modify by ck 20170613    添加设备列表
     */
    public function getBoxStateBySchoolAction()
    {
        $this->view->disable();
        $schoolId = $this->request->getPost('iSchoolId', 'int');
        $config = Main::getConfigByName('cBoxUrl');
        $gmClient = new GmClient();
        $gmClient->connect($config['ip'], $config['port']) or die(Main::showMessageModal('盒子连接失败！', 109110024));
        $gmClient->writeAndReadChatMsg('//gm getGtBoxStatus ' . $schoolId, $resRequest);
        $resRequest = $this->transformEncodeAndEnter($resRequest[0]);
        $gmClient->writeAndReadChatMsg('//gm getBoxSrcList ' . $schoolId, $resList);
        $resList = $this->transformEncodeAndEnter($resList);
        $gmClient->writeAndReadChatMsg('//gm getBoxNgxLog ' . $schoolId, $nginxLog);
        $nginxLog = $this->transformEncodeAndEnter($nginxLog[0]);
        $gmClient->writeAndReadChatMsg('//gm getSchlDev ' . $schoolId, $devList);
        $devList = $this->transformEncodeAndEnter($devList[0]);
        return $this->response->setJsonContent([
            'resRequest'=> $resRequest,
            'resList'   => $resList,
            'nginxLog'  => $nginxLog,
            'devList'   => $devList
        ]);
    }

    private function transformEncodeAndEnter($obj)
    {
        if (is_array($obj)) {
            $obj = implode('<br />', $obj);
        }
        $obj = iconv('gbk', 'utf-8', $obj);
        $obj = str_replace("\n", '<br />', $obj);
        return $obj;
    }

    /**
     * 获取盒子http对象
     *
     * @return bool|HttpClient
     *
     * create by ck 20170817
     */
    private function getBoxHttpClient()
    {
        static $httpClient;
        if (empty($httpClient)) {
            $url = Main::getConfigByName('box')['url'];
            if (!$url) {
                return false;
            }
            $httpClient = new HttpClient($url);
        }
        return $httpClient;
    }

    /**
     * 盒子列表
     *
     * @return bool|string
     *
     * create by ck 20170817
     */
    public function boxAction()
    {
        $this->view->setTemplateBefore('listForm');
        Main::showNavPosition();
        Assets::easyUI('js/server/box.js');
        if (!Power::exist('Server_BoxList')) {
            return $this->sendViewError('无查看此页面权限！');
        }
        $boxButtonArr = [];
        $boxButtonArr[] = ['id' => 'bt_list_state', 'text' => '查看状态', 'icon' => 'fa-eye'];
        $boxButtonArr[] = ['id' => 'bt_list_push', 'text' => '推送资源', 'icon' => 'fa-send'];
        $boxButtonArr[] = ['id' => 'bt_list_update', 'text' => '更新服务', 'icon' => 'fa-level-up'];
        $this->view->setVars([
            'List'  => Template::createList('list', 'Server_Box', [
                'buttonToolbar' => Template::createButtonToolBar($boxButtonArr)
            ]),
        ]);
        return true;
    }

    /**
     * 获取盒子信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170817
     * modify by ck 20170823
     */
    public function getBoxAction()
    {
        $httpClient = $this->getBoxHttpClient();
        $response   = $httpClient->get('/api/v1/box/manage/boxs', [
            'currentPage'   => $this->request->getPost('page', 'int'),
            'size'          => $this->request->getPost('rows', 'int')
        ]);
        if (!$response->isSuccess()) {
            return $this->sendErrorResponse(500, '获取盒子列表失败！', $response);
        }
        $body = $response->toArray();
        Tool::runTimestamp($body['data'], 'regTime');
        Main::runSchoolNameByIdStr($body['data'], ['schoolId' => 'schoolName'], true);
        Tool::runEnum($body['data'], $this->boxEnum);

        //添加网络状态
        foreach ($body['data'] as $index => $row) {
            $body['data'][$index]['netStatus']      = '<i class="fa fa-spinner fa-spin"></i>';
            $body['data'][$index]['residualSpace'] .= 'MB';
        }

        return $this->sendJsonResponse(['total' => $body['page']['total'], 'rows' => $body['data']]);
    }

    /**
     * 获取盒子网络状态
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170823
     * modify by ck 20180123    更改网络状态结构
     */
    public function getBoxNetAction()
    {
        $config  = Main::getConfigByName('box');
        $netInfo = file($config['netUrl']);
        if (!$netInfo) {
            return $this->sendErrorResponse(500, '网络状态获取失败！', '地址：' . $config['netUrl']);
        }
        $result = [];
        foreach ($netInfo as $info) {
            $info = explode(':', $info);
            if (!isset($info[1])) {
                continue;
            }
            $port = $info[0];
            if (!is_numeric($port)) {
                continue;
            }
            if (trim($info[1]) == 'online') {
                $result[$port] = 'success';
            } else {
                $result[$port] = 'warning';
            }
        }
//        foreach($netInfo as $info){
//            $info = explode(' ', $info);
//            if(!isset($info[2])) continue;
//            $port = explode(':', $info[3]);
//            $port = trim(end($port));
//            if(!is_numeric($port)) continue;
//            if($info[2] == '[SUCCESS]'){
//                $result[$port] = 'success';
//            }
//            else{
//                $result[$port] = 'warning';
//            }
//        }
        return $this->sendJsonResponse($result);
    }

    /**
     * 推送资源到盒子
     *
     * @param int $type
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170817
     */
    public function pushBoxResourceAction($type = 2)
    {
        if (!Power::exist('Server_BoxList_Add')) {
            return $this->sendErrorResponse(403, '无推送权限！');
        }
        $httpClient     = $this->getBoxHttpClient();
        $day            = $this->request->getPost('day', 'int', 7);
        $urls           = $this->request->getPost('url', 'string');     //清除html实体
        $md5s           = $this->request->getPost('md5', 'string');
        $packages       = $this->request->getPost('packageName', 'string');
        $versionCodes   = $this->request->getPost('versionCode', 'int');
        $versionNames   = $this->request->getPost('versionName', 'string');
        $createTime     = time();
        $expirationTime = strtotime("+{$day} days", $createTime);
        $resourceList   = [];
        if (!in_array($type, [0, 1, 2])) {
            return $this->sendErrorResponse(400, '类型不正确！');
        }
        if (empty($urls) || empty($md5s)) {
            return $this->sendErrorResponse(400, '缺少参数！');
        }
        if (count($urls) != count($md5s)) {
            return $this->sendErrorResponse(400, '参数不完整！', 'url及md5数量不匹配！');
        }
        for ($i = 0; $i < count($urls); $i++) {
            $tempResource = [
                'type'  => $type,
                'url'   => stripslashes($urls[$i]),
                'md5'   => $md5s[$i],
            ];
            isset($packages[$i])     and $tempResource['apkPackage']     = $packages[$i];
            isset($versionCodes[$i]) and $tempResource['apkVersionCode'] = intval($versionCodes[$i]);
            isset($versionNames[$i]) and $tempResource['apkVersionName'] = $versionNames[$i];
            $resourceList[] = $tempResource;
        }
        $response = $httpClient->postJson('/api/v1/box/manage/resource', [
            'createTime'            => $createTime * 1000,
            'expirationTime'        => $expirationTime * 1000,
            'resourceInfoDtoList'   => $resourceList
        ]);
        if (!$response->isSuccess()) {
            $body = $response->toObject();
            return $this->sendErrorResponse(500, '推送失败！' . $body->msg, $response);
        }
        return $this->sendSuccessResponse('推送成功！');
    }

    /**
     * 盒子状态页面
     *
     * create by ck 20170820
     */
    public function boxStateAction()
    {
        $this->view->pick('server/boxState');
        Assets::importJs('js/server/boxState.js');
    }

    /**
     * 获取盒子状态
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170820
     */
    public function getBoxStateAction()
    {
        $mac    = $this->request->getPost('mac', 'string');
        $target = $this->request->getPost('target', 'string');
        if (!$mac || !$target) {
            return $this->sendErrorResponse(400, '参数不完整');
        }
        $httpClient = $this->getBoxHttpClient();
        $response   = $httpClient->get(sprintf("/api/v1/box/manage/%s/{$target}", $mac), [
            'currentPage'   => $this->request->getPost('page', 'int', 1),
            'size'          => $this->request->getPost('size', 'int', 20)
        ]);
        if (!$response->isSuccess()) {
            return $this->sendErrorResponse(500, '数据获取失败！', $response);
        }
        $body = $response->toArray();
        Tool::runTimestamp($body['data'], ['timestamp', 'time', 'timeBegin', 'timeEnd']);
        return $this->sendJsonResponse($body['data']);
    }

    /**
     * 更新盒子版本
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170821
     */
    public function updateBoxVersionAction()
    {
        set_time_limit(0);
        if (!Power::exist('Server_BoxList_Edit')) {
            return $this->sendErrorResponse(403, '无更新权限！');
        }
        $version = $this->request->getPost('version', 'string');
        if (!$version) {
            return $this->sendErrorResponse(400, '缺少版本信息');
        }
        if (!$this->request->hasFiles()) {
            return $this->sendErrorResponse(400, '缺少文件');
        }
        $file = $this->request->getUploadedFiles()[0];
        if ($file->getExtension() != 'jar') {
            return $this->sendErrorResponse(400, '文件类型不正确');
        }
        $filePath = Tool::buildPath(Main::getConfigByName('fileSave')['temp'], $file->getName());
        $file->moveTo($filePath);
        $url = Main::uploadToFileManageSystem($filePath, 'jar');
        if (!$url) {
            return $this->sendErrorResponse(500, '文件上传失败');
        }
        $httpClient = $this->getBoxHttpClient();
        $response = $httpClient->postJson('/api/v1/box/manage/new/version', [
            'timestamp' => time() * 1000,
            'url'       => $url,
            'version'   => $version
        ]);
        if (!$response->isSuccess()) {
            return $this->sendErrorResponse(500, '更新失败', $response);
        }
        return $this->sendSuccessResponse('更新成功');
    }

}

